package shapewar.view.myview;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Path;
import shapewar.conf.Conf;
import shapewar.engine.calc.Pos;
import shapewar.engine.model.abst.Model;
import shapewar.engine.model.abst.ModelAdapter;
import shapewar.engine.presenter.EngineThread;
import shapewar.engine.presenter.Presenter;
import shapewar.view.intefac.OnClickedListener;

public class MyButton extends MyView {
	public OnClickedListener listener;
	private String txt = new String();
	private float l;
	final int init_bg_color = Color.BLUE;//Color.rgb(55,55,55);
	final int init_txt_color = Color.WHITE;
	int bg_color = init_bg_color;
	int txt_color = Color.WHITE;
	int bg_alpha = 220;
	int txt_alpha = 255;
	Model shape = getModel();
	private boolean enable = true;
	public MyButton(Presenter pst,float x,float y,float width,float height) {
		super(pst, new ModelAdapter(pst,-1, x, y, new float[][]{
				{-width/2,height/2},
				{width/2,height/2},
				{width/2,-height/2},
				{-width/2,-height/2}
		}, Conf.depth_button){
			@Override
			public void init() {
				
			}

			@Override
			public void destory() {
				
			}
			
		});
	}
	
	public void init(){
		pst.bridge.addView(this);
	}
	
	public void remove(){
		pst.bridge.removeView(this);
	}
	
	public void setText(String txt,int size){
		this.txt = txt;
		paint.setTextSize(size);
		this.l = paint.measureText(txt);
		invalidate();
	}
	
	public void setBackgroundColor(int color){
		this.bg_color = color;
		invalidate();
	}
	
	public void setTextColor(int color) {
		this.txt_color = color;
		invalidate();
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		paint.setColor(bg_color);
		paint.setAlpha(bg_alpha);
		paint.setAntiAlias(true); 
		Path path = new Path();
		path.moveTo(shape._x + shape.v[0][0], shape._y + shape.v[0][1]);
		for(int i=1;i<shape.v.length;i++){
			path.lineTo(shape._x + shape.v[i][0], shape._y + shape.v[i][1]);
		}
		canvas.drawPath(path, paint);
		paint.setColor(txt_color);
		paint.setAlpha(txt_alpha);
		//paint.setMaskFilter(PaintFilter.getMaskFilter());
		canvas.drawText(txt, shape._x - l/2, shape._y+Conf.SIZE*2, paint);
	}
	
	@Override
	public Pos getRelativePos() {
		return new Pos(shape._x,shape._y);
	}
	
	public void touched(float x,float y){
		if(!enable)return;
		new EngineThread(15) {
			int i = 0;
			@Override
			public void repeat() {
				setBackgroundColor(Color.GRAY);
				if(++i%2==0){
					setBackgroundColor(init_bg_color);
					this.destory();
				}
			}
		}.start();
		listener.onClicked(x, y);
	}
	
	public void enable(boolean bo){
		this.enable = bo;
		if(enable){
			bg_alpha = 200;
		}else{
			bg_alpha = 50;
		}
		invalidate();
	}
}
